package com.vay.de.dang.online.view;

import android.content.Context;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import com.vay.de.dang.online.util.CameraHelper;

public class CameraPreviewView extends SurfaceView implements SurfaceHolder.Callback {

    private SurfaceHolder surfaceHolder;
    private int cameraId = 0;
    private int viewWidth;
    private int viewHeight;

    public CameraPreviewView(Context context) {
        super(context);
        init();
    }

    public CameraPreviewView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CameraPreviewView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        surfaceHolder = getHolder();
        surfaceHolder.addCallback(this);
        setOnClickListener(v -> {
            CameraHelper.requestFocus();
        });
    }

    public void setCameraId(int id) {
        cameraId = id;
    }

    public void switchCamera() {
        cameraId = (++cameraId) % 2;
        CameraHelper.switchCamera(cameraId, surfaceHolder);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        viewWidth = width;
        viewHeight = height;
        openCamera();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        CameraHelper.releaseCamera();
    }

    public void openCamera() {
        if (CameraHelper.openCamera(cameraId, viewWidth, viewHeight, 24)) {

            // 矩阵变化
            Camera.Size size = CameraHelper.getPreviewSize();
            Matrix matrix = CameraHelper.configureTransform(size.width, size.height, viewWidth, viewHeight);
            float[] values = new float[9];
            matrix.getValues(values);
            setTranslationX(values[Matrix.MTRANS_X]);
            setTranslationY(values[Matrix.MTRANS_Y]);
            setScaleX(values[Matrix.MSCALE_X]);
            setScaleY(values[Matrix.MSCALE_Y]);
            invalidate();

            CameraHelper.startPreviewDisplay(surfaceHolder);
        }
    }
}
